import { MenuState } from "@/store/modules/auth"
import { isEmpty, isObject, log } from "@/utils"
import { RouteRecordRaw } from "vue-router"
import router from "@/router"
import { staticMenus } from "./static-menu"

const LayoutMap: Recordable = {
    Layout: () => import("@/layout/Index.vue"),
    EmptyLayout: () => import("@/layout/Empty.vue")
}

export const createDynamisRouter = (menus: MenuState[], permissions: string[]): RouteRecordRaw[] => {
    menus.unshift(...staticMenus)
    const routes = import.meta.env.VITE_USE_STATIC_ROUTE === true ? globRoutes(permissions) : generateRoutes(menus)
    routes.forEach(v => router.addRoute(v))
    log.info("动态加载路由")
    return routes
}

/**
 * 生成动态路由
 */
const generateRoutes = (menus: MenuState[], parent?: MenuState): RouteRecordRaw[] => {
    return menus.map(menu => {
        const path = determineRoutePath(menu, parent)
        menu.path = path
        const route: any = {
            // 路由地址
            path,
            // 路由名称，建议唯一
            name: menu.code ?? "",
            meta: {
                ...menu.meta,
                // 页面标题
                title: menu.name,
                // 菜单图标
                icon: menu.icon ?? null,
                // 是否显示为菜单
                show: menu.show === true,
                // 登录校验
                needLogin: true
            }
        }
        if (!isEmpty(menu.redirect)) {
            route.redirect = menu.redirect
        }
        if (menu.component) {
            if (menu.component.startsWith("/")) {
                route.component = () => import(`/src/views${menu.component}`).then(component => ({ ...component.default, name: menu.code }))
            } else {
                route.component = LayoutMap[menu.component]
            }
        }
        if (!isEmpty(menu.children)) {
            route.children = generateRoutes(menu.children ?? [], menu)
            if (isEmpty(route.redirect) && !isEmpty(route.children)) {
                const firstChild = route.children.find((v: any) => v.meta.show)
                if (isObject(firstChild)) {
                    route.redirect = firstChild.path
                }
            }
        }
        return route as RouteRecordRaw
    })
}

/**
 * 确定当前菜单的访问路径
 */
function determineRoutePath(menu: MenuState, parent?: MenuState) {
    if (menu.path.startsWith("/")) {
        return menu.path
    } else {
        return `${(parent && parent.path) ?? ""}/${menu.path}`
    }
}

/**
 * 扫描本地模块路由
 */
function globRoutes(permissions: string[]): RouteRecordRaw[] {
    console.log(permissions)

    // const modules = import.meta.glob<RouteRecordRaw | RouteRecordRaw[]>("./modules/**/*.ts", { import: "default", eager: true })

    // Object.keys(modules).forEach(key => {
    //     console.log(key)
    // })

    return []
}
